package articles_api

import (
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"gin_study_blog/utils"
	"github.com/gin-gonic/gin"
)

// ArticleCollectsCreateView 用户收藏或取消
func (ArticlesApi) ArticleCollectsCreateView(c *gin.Context) {
	var cr models.EsIDRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		http.FailWithCode(http.ParamsError, c)
		return
	}

	_claims, _ := c.Get("user")
	claims := _claims.(*utils.UserClaims)

	detail, err := utils.CommDetail(cr.ID)
	if err != nil {
		common.Log.Error(err)
		http.FailWithMessage("文章不存在", c)
		return
	}

	var coll models.UserCollectsModel
	err = common.DB.Take(&coll, "user_id = ? AND article_id = ?", claims.UserID, cr.ID).Error
	var num = -1
	if err != nil {
		// 没有找到, 收藏文章
		err = common.DB.Create(&models.UserCollectsModel{
			UserID:    claims.UserID,
			ArticleID: cr.ID,
		}).Error
		if err != nil {
			common.Log.Error(err.Error())
			http.FailWithMessage("文章收藏失败", c)
			return
		}
		num = 1
	}
	// 找到了, 取消收藏
	common.DB.Delete(&coll)

	err = ArticleModify(cr.ID, map[string]any{
		"collects_count": detail.CollectsCount + num,
	})
	if err != nil {
		common.Log.Error(err)
		http.FailWithMessage("更新失败", c)
		return
	}
	if num == 1 {
		http.IsOkWithMessage("文章收藏成功", c)
	} else {
		http.IsOkWithMessage("取消文章收藏", c)
	}
}
